package com.css.zfzx.fwsjcj.modules.taskmanage.taskfrom.service.Impl;


import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.org.division.repository.entity.DivisionEntity;
import com.css.bpm.platform.org.user.repository.entity.UserEntity;
import com.css.bpm.platform.utils.PlatformObjectUtils;
import com.css.bpm.platform.utils.PlatformSessionUtils;
import com.css.bpm.platform.utils.UUIDGenerator;
import com.css.zfzx.fwsjcj.cache.DivisionCache;
import com.css.zfzx.fwsjcj.commen.util.Constant;
import com.css.zfzx.fwsjcj.commen.util.EasyPoiExcelUtil;
import com.css.zfzx.fwsjcj.commen.util.SpringUtil;
import com.css.zfzx.fwsjcj.modules.analysis.vo.AnalysisQueryVo;
import com.css.zfzx.fwsjcj.modules.taskmanage.taskfrom.entity.FwCtiyHouseEntity;
import com.css.zfzx.fwsjcj.modules.taskmanage.taskfrom.entity.FwFormEntity;
import com.css.zfzx.fwsjcj.modules.taskmanage.taskfrom.repository.CityTaskRepository;
import com.css.zfzx.fwsjcj.modules.taskmanage.taskfrom.service.CityTaskFormService;
import com.css.zfzx.fwsjcj.modules.taskmanage.taskfrom.service.ImageFormService;
import com.css.zfzx.fwsjcj.modules.taskmanage.taskfrom.service.TaskFromService;
import com.css.zfzx.fwsjcj.modules.taskmanage.taskfrom.vo.CityTaskVo;
import com.css.zfzx.fwsjcj.modules.taskmanage.taskfrom.verify.CityHouseCheck;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.criteria.*;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
@Slf4j
@Service
public class CityTaskFormServiceImpl implements CityTaskFormService {
    @Autowired
    CityTaskRepository cityTaskRepository;
    @Autowired
    TaskFromService taskFromService;
    @Autowired
    ImageFormService imageFormService;
    private volatile static HashMap<String, List> divisionMap;
    @Override
    public void saveFrom(FwCtiyHouseEntity fwCtiyHouseEntity, String type) {
        String uuid = UUIDGenerator.getUUID();
        UserEntity user = PlatformAPI.getOrgAPI().getUserAPI().getUser(PlatformSessionUtils.getUserId());
        Date date = new Date();
        fwCtiyHouseEntity.setFwId(uuid);
        fwCtiyHouseEntity.setCreateTime(date);
        fwCtiyHouseEntity.setIsValid(Constant.IS_VALID_YES);
        fwCtiyHouseEntity.setSaveStatus(type);
        fwCtiyHouseEntity.setSpType(type);
        fwCtiyHouseEntity.setCollecDate(date);

        FwFormEntity fwFormEntity = new FwFormEntity();

        if(fwCtiyHouseEntity.getCreateUserId()==null){
            fwCtiyHouseEntity.setCreateUserId(PlatformSessionUtils.getUserId());
            fwCtiyHouseEntity.setCollecPerson(user.getUserName());
            fwFormEntity.setDataSources("0");
        }else{
            fwFormEntity.setCreateUserId(fwCtiyHouseEntity.getCreateUserId());
            fwFormEntity.setCollecPerson(fwCtiyHouseEntity.getCollecPerson());
            fwFormEntity.setDataSources("1");
        }

        fwFormEntity.setTaskId(fwCtiyHouseEntity.getTaskId());
        fwFormEntity.setTaskName(fwCtiyHouseEntity.getTaskName());
        fwFormEntity.setCreateTime(date);
        fwFormEntity.setFormId(uuid);
        fwFormEntity.setBuildingName(fwCtiyHouseEntity.getBuildingName());
        fwFormEntity.setBulidingLatitude(fwCtiyHouseEntity.getBulidingLatitude());
        fwFormEntity.setBulidingLongitude(fwCtiyHouseEntity.getBulidingLongitude());
        fwFormEntity.setBulidingType(Constant.BULIDING_CITY);
        fwFormEntity.setTaskId(fwCtiyHouseEntity.getTaskId());
        fwFormEntity.setSpType(type);
        fwFormEntity.setBuildingCode(fwCtiyHouseEntity.getBuildingCode());
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(fwCtiyHouseEntity.getBelongtoProvince() + ",");
        stringBuilder.append(fwCtiyHouseEntity.getBelongtoCity() + ",");
        stringBuilder.append(fwCtiyHouseEntity.getBelongtoArea());
        fwFormEntity.setBuildingAddress(stringBuilder.toString());
        fwFormEntity.setTaskName(fwCtiyHouseEntity.getTaskName());
        fwFormEntity.setIsSaveAll(fwCtiyHouseEntity.getIsSaveAll());
        fwFormEntity.setBelongtoProvince(fwCtiyHouseEntity.getBelongtoProvince());
        fwFormEntity.setBelongtoCity(fwCtiyHouseEntity.getBelongtoCity());
        fwFormEntity.setBelongtoArea(fwCtiyHouseEntity.getBelongtoArea());
        taskFromService.saveForm(fwFormEntity);
        cityTaskRepository.save(fwCtiyHouseEntity);
    }

    @Override
    public FwCtiyHouseEntity findCityById(String formId) {
        FwCtiyHouseEntity fwCtiyHouseEntity = cityTaskRepository.findById(formId).get();
        return fwCtiyHouseEntity;
    }


    @Override
    public List<FwCtiyHouseEntity> findCitys() {
        List<FwCtiyHouseEntity> fwCtiyHouseEntitys = cityTaskRepository.findAll();
        return fwCtiyHouseEntitys;
    }

    @Transactional
    @Override
    public void subById(String id, String type) {
        cityTaskRepository.suById(type, id);
    }

    @Override
    public void deleteById(String id) {
        cityTaskRepository.deletByFromId(id);
    }

    @Transactional
    @Override
    public void updCity(String type, FwCtiyHouseEntity fwCtiyHouseEntity) {
        FwCtiyHouseEntity cityById = findCityById(fwCtiyHouseEntity.getFwId());
        // 只忽略null值
        SpringUtil.copyPropertiesIgnoreNull(fwCtiyHouseEntity, cityById);
        cityById.setSpType(type);
        // 主表
        FwFormEntity byFormId = taskFromService.findByFormId(fwCtiyHouseEntity.getFwId());
        byFormId.setSpType(type);
        byFormId.setIsSaveAll(fwCtiyHouseEntity.getIsSaveAll());
        byFormId.setBulidingLongitude(fwCtiyHouseEntity.getBulidingLongitude());
        byFormId.setBulidingLatitude(fwCtiyHouseEntity.getBulidingLatitude());
        byFormId.setBuildingName(fwCtiyHouseEntity.getBuildingName());
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(fwCtiyHouseEntity.getBelongtoProvince() + ",");
        stringBuilder.append(fwCtiyHouseEntity.getBelongtoCity() + ",");
        stringBuilder.append(fwCtiyHouseEntity.getBelongtoArea());
        byFormId.setIsValid(cityById.getIsValid());
        byFormId.setBelongtoProvince(fwCtiyHouseEntity.getBelongtoProvince());
        byFormId.setBelongtoCity(fwCtiyHouseEntity.getBelongtoCity());
        byFormId.setBelongtoArea(fwCtiyHouseEntity.getBelongtoArea());
        taskFromService.updForm(byFormId);
        cityTaskRepository.save(cityById);
    }

    @Transactional
    @Override
    public void spReason(String status, String reason, String formId) {
        cityTaskRepository.spReason(status, reason, formId);
    }

    @Override
    public long count(AnalysisQueryVo analysisQueryVo) {
        // 查询条件
        Specification querySpecification = new Specification<FwCtiyHouseEntity>() {
            @Override
            public Predicate toPredicate(Root<FwCtiyHouseEntity> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                if (analysisQueryVo != null) {
                    // 省
                    String belongtoProvince = analysisQueryVo.getBelongtoProvince();
                    if (!StringUtils.isEmpty(belongtoProvince)) {
                        predicates.add(criteriaBuilder.equal(root.get("belongtoProvince"), belongtoProvince));
                    }
                    // 市
                    String belongtoCity = analysisQueryVo.getBelongtoCity();
                    if (!StringUtils.isEmpty(belongtoCity)) {
                        predicates.add(criteriaBuilder.equal(root.get("belongtoCity"), belongtoCity));
                    }
                    // 区
                    String belongtoArea = analysisQueryVo.getBelongtoArea();
                    if (!StringUtils.isEmpty(belongtoArea)) {
                        predicates.add(criteriaBuilder.equal(root.get("belongtoArea"), belongtoArea));
                    }
                    //任务名称
                    String taskName = analysisQueryVo.getTaskName();
                    if (!org.apache.commons.lang3.StringUtils.isEmpty(taskName)) {
                        String[] strArray = taskName.split(",");
                        List<String> list = Arrays.asList(strArray);
                        if (list != null && list.size() > 0){
                            predicates.add(root.get("taskName").in(list));
                        }
                    }
                    // 审批类型
                    String spType = analysisQueryVo.getSpType();
                    if (!StringUtils.isEmpty(spType)) {
                        if ("审核通过".equals(spType)) {
                            // 若为审核通过，查询spType审批状态为3
                            predicates.add(criteriaBuilder.equal(root.get("spType"), Constant.SP_YES));
                        } else if ("质检通过".equals(spType)) {
                            // 若为质检通过，查询qualityStatus质检状态为2
                            predicates.add(criteriaBuilder.equal(root.get("qualityStatus"), Constant.HOUSE_QUALITY_STATUS_SUCCESS));
                        } else {
                            // 1 2 3
                            predicates.add(criteriaBuilder.equal(root.get("spType"), spType));
                        }
                    }
                    // 结构类型
                    String structureType = analysisQueryVo.getStructureType();
                    if (!StringUtils.isEmpty(structureType)) {
                        predicates.add(criteriaBuilder.equal(root.get("structureType"), structureType));
                    }
                    // 建造时间
                    String buildingTime = analysisQueryVo.getBuildingTime();
                    if (!StringUtils.isEmpty(buildingTime)) {
                        predicates.add(criteriaBuilder.equal(root.get("buildingTime"), buildingTime));
                    }
                    // 现设防烈度
                    String nowFortificationIntensity = analysisQueryVo.getNowFortificationIntensity();
                    if (!StringUtils.isEmpty(nowFortificationIntensity)) {
                        predicates.add(criteriaBuilder.like(root.get("nowFortificationIntensity"), "%" + nowFortificationIntensity + "%"));
                    }
                    //初步结论（未抗震设防 抗震设防能力不足 基本符合抗震设防要求）
                    String result = analysisQueryVo.getResult();
                    if (!StringUtils.isEmpty(result)) {
                        predicates.add(criteriaBuilder.equal(root.get("result"), result));
                    }
                    // 房屋使用情况 (农村住房:自用/空置/出租/经营/被征或待征/其他)
                    String houseUseSituation = analysisQueryVo.getHouseUseSituation();
                    if (!StringUtils.isEmpty(houseUseSituation)) {
                        predicates.add(criteriaBuilder.equal(root.get("houseUseSituation"), houseUseSituation));
                    }
                    // 居住房屋抗震构造措施 (农村住房:正规设计建造 有圈梁构造柱等整体性连接措施 已实施抗震加固 其他抗震措施)
                    String houseMeasures = analysisQueryVo.getHouseMeasures();
                    if (!StringUtils.isEmpty(houseMeasures)) {
                        predicates.add(criteriaBuilder.equal(root.get("houseMeasures"), houseMeasures));
                    }
                    // 居住房屋有无明显可见的裂缝、变形、倾斜等（城镇住宅、城镇非住宅、农村公共建筑）
                    String isDamage = analysisQueryVo.getIsDamage();
                    if (!StringUtils.isEmpty(isDamage)) {
                        predicates.add(criteriaBuilder.equal(root.get("isDamage"), isDamage));
                    }
                    // 采集时间 collecDate
                    Date beginDate = analysisQueryVo.getBeginDate();
                    Date endDate = analysisQueryVo.getEndDate();
                    if (beginDate != null && endDate != null) {
                        predicates.add(criteriaBuilder.between(root.<Date>get("collecDate"), beginDate, endDate));
                    }
                    if (beginDate != null && endDate == null) {
                        predicates.add(criteriaBuilder.greaterThanOrEqualTo(root.<Date>get("collecDate"), beginDate));
                    }
                    if (beginDate == null && endDate != null) {
                        predicates.add(criteriaBuilder.lessThanOrEqualTo(root.<Date>get("collecDate"), endDate));
                    }
                }
                // 有效标识，即为有效的
                predicates.add(criteriaBuilder.equal(root.get("isValid"), Constant.IS_VALID_YES));
                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
        return cityTaskRepository.count(querySpecification);
    }

    @Override
    public int areaCount(AnalysisQueryVo analysisQueryVo) {
        // 查询条件

        Specification querySpecification = new Specification<FwCtiyHouseEntity>() {
            @Override
            public Predicate toPredicate(Root<FwCtiyHouseEntity> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                if (analysisQueryVo != null) {
                    // 省
                    String belongtoProvince = analysisQueryVo.getBelongtoProvince();
                    if (!StringUtils.isEmpty(belongtoProvince)) {
                        predicates.add(criteriaBuilder.equal(root.get("belongtoProvince"), belongtoProvince));
                    }
                    // 市
                    String belongtoCity = analysisQueryVo.getBelongtoCity();
                    if (!StringUtils.isEmpty(belongtoCity)) {
                        predicates.add(criteriaBuilder.equal(root.get("belongtoCity"), belongtoCity));
                    }
                    // 区
                    String belongtoArea = analysisQueryVo.getBelongtoArea();
                    if (!StringUtils.isEmpty(belongtoArea)) {
                        predicates.add(criteriaBuilder.equal(root.get("belongtoArea"), belongtoArea));
                    }
                    //任务名称
                    String taskName = analysisQueryVo.getTaskName();
                    if (!org.apache.commons.lang3.StringUtils.isEmpty(taskName)) {
                        String[] strArray = taskName.split(",");
                        List<String> list = Arrays.asList(strArray);
                        if (list != null && list.size() > 0){
                            predicates.add(root.get("taskName").in(list));
                        }
                    }
                    // 审批类型
                    String spType = analysisQueryVo.getSpType();
                    if (!StringUtils.isEmpty(spType)) {
                        if ("审核通过".equals(spType)) {
                            // 若为审核通过，查询spType审批状态为3
                            predicates.add(criteriaBuilder.equal(root.get("spType"), Constant.SP_YES));
                        } else if ("质检通过".equals(spType)) {
                            // 若为质检通过，查询qualityStatus质检状态为2
                            predicates.add(criteriaBuilder.equal(root.get("qualityStatus"), Constant.HOUSE_QUALITY_STATUS_SUCCESS));
                        } else {
                            // 1 2 3
                            predicates.add(criteriaBuilder.equal(root.get("spType"), spType));
                        }
                    }
                    // 结构类型
                    String structureType = analysisQueryVo.getStructureType();
                    if (!StringUtils.isEmpty(structureType)) {
                        predicates.add(criteriaBuilder.equal(root.get("structureType"), structureType));
                    }
                    // 建造时间
                    String buildingTime = analysisQueryVo.getBuildingTime();
                    if (!StringUtils.isEmpty(buildingTime)) {
                        predicates.add(criteriaBuilder.equal(root.get("buildingTime"), buildingTime));
                    }
                    // 现设防烈度
                    String nowFortificationIntensity = analysisQueryVo.getNowFortificationIntensity();
                    if (!StringUtils.isEmpty(nowFortificationIntensity)) {
                        predicates.add(criteriaBuilder.like(root.get("nowFortificationIntensity"), "%" + nowFortificationIntensity + "%"));
                    }
                    //初步结论（未抗震设防 抗震设防能力不足 基本符合抗震设防要求）
                    String result = analysisQueryVo.getResult();
                    if (!StringUtils.isEmpty(result)) {
                        predicates.add(criteriaBuilder.equal(root.get("result"), result));
                    }
                    // 房屋使用情况 (农村住房:自用/空置/出租/经营/被征或待征/其他)
                    String houseUseSituation = analysisQueryVo.getHouseUseSituation();
                    if (!StringUtils.isEmpty(houseUseSituation)) {
                        predicates.add(criteriaBuilder.equal(root.get("houseUseSituation"), houseUseSituation));
                    }
                    // 居住房屋抗震构造措施 (农村住房:正规设计建造 有圈梁构造柱等整体性连接措施 已实施抗震加固 其他抗震措施)
                    String houseMeasures = analysisQueryVo.getHouseMeasures();
                    if (!StringUtils.isEmpty(houseMeasures)) {
                        predicates.add(criteriaBuilder.equal(root.get("houseMeasures"), houseMeasures));
                    }
                    // 居住房屋有无明显可见的裂缝、变形、倾斜等（城镇住宅、城镇非住宅、农村公共建筑）
                    String isDamage = analysisQueryVo.getIsDamage();
                    if (!StringUtils.isEmpty(isDamage)) {
                        predicates.add(criteriaBuilder.equal(root.get("isDamage"), isDamage));
                    }
                    // 采集时间 collecDate
                    Date beginDate = analysisQueryVo.getBeginDate();
                    Date endDate = analysisQueryVo.getEndDate();
                    if (beginDate != null && endDate != null) {
                        predicates.add(criteriaBuilder.between(root.<Date>get("collecDate"), beginDate, endDate));
                    }
                    if (beginDate != null && endDate == null) {
                        predicates.add(criteriaBuilder.greaterThanOrEqualTo(root.<Date>get("collecDate"), beginDate));
                    }
                    if (beginDate == null && endDate != null) {
                        predicates.add(criteriaBuilder.lessThanOrEqualTo(root.<Date>get("collecDate"), endDate));
                    }
                }
                // 有效标识，即为有效的
                predicates.add(criteriaBuilder.equal(root.get("isValid"), Constant.IS_VALID_YES));
                Predicate predicate = criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
                return predicate;
            }
        };
        List<FwCtiyHouseEntity> all = cityTaskRepository.findAll(querySpecification);
        int count = 0;
        for (FwCtiyHouseEntity fwCtiyHouseEntity : all) {
            int buildingArea = 0;
            int upbuildingArea = 0;
            int downbuildingArea = 0;
            if (PlatformObjectUtils.isNotEmpty(fwCtiyHouseEntity.getBuildingArea())) {
                buildingArea = fwCtiyHouseEntity.getBuildingArea().intValue();
                if (PlatformObjectUtils.isNotEmpty(fwCtiyHouseEntity.getBuildingUpNum())){
                    upbuildingArea = (fwCtiyHouseEntity.getBuildingArea().intValue()
                            * fwCtiyHouseEntity.getBuildingUpNum().intValue());
                }
                if(PlatformObjectUtils.isNotEmpty(fwCtiyHouseEntity.getBuildingDown())){
                    downbuildingArea = buildingArea + (fwCtiyHouseEntity.getBuildingArea().intValue()
                            * fwCtiyHouseEntity.getBuildingDown().intValue());
                }
                buildingArea = upbuildingArea + downbuildingArea;
            }
            count += buildingArea;
        }
        return count;
    }

    @Override
    @Transactional
    public void update(FwCtiyHouseEntity fwCtiyHouseEntity) {
        // 子表
        FwCtiyHouseEntity cityById = findCityById(fwCtiyHouseEntity.getFwId());
        // 将不为空的属性拷贝到cityById旧对象中
        SpringUtil.copyPropertiesIgnoreEmpty(fwCtiyHouseEntity, cityById);
        cityTaskRepository.save(cityById);

        // 主表
        FwFormEntity byFormId = taskFromService.findByFormId(fwCtiyHouseEntity.getFwId());
        FwFormEntity fwFormEntity = new FwFormEntity();
        // 建筑名称
        fwFormEntity.setBuildingName(fwCtiyHouseEntity.getBuildingName());
        // 省市区
        fwFormEntity.setBulidingLongitude(fwCtiyHouseEntity.getBulidingLongitude());
        fwFormEntity.setBulidingLatitude(fwCtiyHouseEntity.getBulidingLatitude());
        fwFormEntity.setBelongtoProvince(fwCtiyHouseEntity.getBelongtoProvince());
        // 经纬度
        fwFormEntity.setBelongtoCity(fwCtiyHouseEntity.getBelongtoCity());
        fwFormEntity.setBelongtoArea(fwCtiyHouseEntity.getBelongtoArea());
        // 设置质检状态和原因
        fwFormEntity.setQualityStatus(fwCtiyHouseEntity.getQualityStatus());
        fwFormEntity.setQualityReason(fwCtiyHouseEntity.getQualityReason());

        SpringUtil.copyPropertiesIgnoreEmpty(fwFormEntity, byFormId);
        taskFromService.updForm(byFormId);

    }

    @Override
    public List<FwCtiyHouseEntity> buildingByBuilding(String buildingName) {
        List<FwCtiyHouseEntity> likeBuidingName = cityTaskRepository.findLikeBuidingName(buildingName);
        return likeBuidingName;
    }

    private int sheetSize = 50000;

    @Override
    public void export(List<String> idList, HttpServletResponse response) {
        List<FwCtiyHouseEntity> fwCtiyHouseEntityList = cityTaskRepository.findInIdList(idList);

        /*List<Map<String, Object>> workbootList = new ArrayList<>();
        int count = fwCtiyHouseEntityList.size() / sheetSize;
        if (fwCtiyHouseEntityList.size() % sheetSize != 0) {
            count = count + 1;
        }
        for (int i = 0; i < count; i++) {
            ExportParams params = new ExportParams();
            params.setSheetName("城镇住宅信息sheet" + (i + 1));

            Map<String, Object> sheetMap = new HashMap<>();
            List<FwCtiyHouseEntity> list = new ArrayList<>();
            if (i * sheetSize + sheetSize > fwCtiyHouseEntityList.size()) {
                list.addAll(fwCtiyHouseEntityList.subList(i * sheetSize, fwCtiyHouseEntityList.size()));
            } else {
                list.addAll(fwCtiyHouseEntityList.subList(i * sheetSize, i * sheetSize + sheetSize));
            }
            sheetMap.put("data", list);
            sheetMap.put("title", params);
            sheetMap.put("entity", FwCtiyHouseEntity.class);
            workbootList.add(sheetMap);
        }*/

        try {
           /* Workbook workbook = ExcelExportUtil.exportExcel(workbootList, ExcelType.XSSF);
            String fileName = "城镇住宅信息";
            fileName = URLEncoder.encode(fileName, "UTF8");
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;chartset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
            ServletOutputStream out = response.getOutputStream();
            workbook.write(out);
            out.flush();
            out.close();*/

            EasyPoiExcelUtil.exportExcel(fwCtiyHouseEntityList, "城镇住宅信息统计", "城镇住宅信息", FwCtiyHouseEntity.class, "城镇住宅信息.xlsx", response);

        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("导出成功");
    }

    @Override
    public List<FwCtiyHouseEntity> findImageURL(List<String> idList) {
        List<FwCtiyHouseEntity> inIdList = cityTaskRepository.findInIdList(idList);
        return inIdList;
    }
    public HashMap<String, List> divisionMap() {
        HashMap<String, List> map = new HashMap<>();
        // 所有省
        List<DivisionEntity> provinceDivisions = PlatformAPI.getDivisionAPI().getSubDivisions("root");
        for (DivisionEntity province : provinceDivisions) {
            String provinceName = province.getDivisionName();
            // 市
            List<DivisionEntity> cities = PlatformAPI.getDivisionAPI().getSubDivisions(province.getDivisionId());
            ArrayList<String> cityNames = new ArrayList<>();
            for (DivisionEntity city : cities) {
                String cityName = city.getDivisionName();
                cityNames.add(cityName);
                // 不为直辖市
                if (!"北京市".equals(provinceName) && !"天津市".equals(provinceName) && !"上海市".equals(provinceName) && !"重庆市".equals(provinceName)) {
                    // 获取市下面的区县
                    List<DivisionEntity> areas = PlatformAPI.getDivisionAPI().getSubDivisions(city.getDivisionId());
                    ArrayList<String> areaNames = new ArrayList<>();
                    for (DivisionEntity area : areas) {
                        String areaName = area.getDivisionName();
                        areaNames.add(areaName);
                    }
                    map.put(cityName, areaNames);
                }
            }
            // 省对应下面的市(直辖市-对应的是区)
            map.put(provinceName, cityNames);
        }
        return map;
    }
    @Override
    public String importCityTask(MultipartFile file, ImportParams params, String taskName, String taskId) {
        // 单例初始化省市区map
        if (divisionMap == null) {
            synchronized (this) {
                if (divisionMap == null) {
                    divisionMap = divisionMap();
                }
            }
        }
        // 返回的消息
        StringBuilder returnMsg = new StringBuilder();
        try {
            params.setVerifyHandler(new CityHouseCheck(divisionMap));
            ExcelImportResult<CityTaskVo> result = ExcelImportUtil.importExcelMore(file.getInputStream(), CityTaskVo.class, params);
            List<CityTaskVo> list = result.getList();
            // Excel条数据
            int firstList = list.size();
            saveFwCityTask(list,taskName,taskId);
            returnMsg.append("成功导入" + result.getList().size() + "条，失败" + result.getFailList().size() + "条<br/>");
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<CityTaskVo> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    CityTaskVo cityTaskVo = iterator.next();
                    returnMsg.append("第" + cityTaskVo.getRowNum() + "行 " + cityTaskVo.getErrorMsg() + "<br/>");
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return "导入失败，请检查数据正确性";
        }
    }
    public void saveFwCityTask(List<CityTaskVo> list,String taskName, String taskId) {
        for (int i = 0; i < list.size(); i++) {
            FwCtiyHouseEntity fwCtiyHouseEntity = new FwCtiyHouseEntity();
            CityTaskVo cityTaskVo = list.get(i);
            if(cityTaskVo.getSuspectedSafetyHazard()!="" && cityTaskVo.getSuspectedSafetyHazard()=="是"){
                cityTaskVo.setResult(cityTaskVo.getResult()+",疑似存在安全隐患");
            }
            String divisionCode=taskFromService.getDivisionCode(cityTaskVo.getBelongtoArea());
            Map<String,Object> userInfo = taskFromService.getUserInfo(cityTaskVo.getUserCode());
            String buildingCode = DivisionCache.getSerialNum(divisionCode);
            fwCtiyHouseEntity.setBuildingCode(buildingCode);
            if(userInfo.get("userId")!=null){
                fwCtiyHouseEntity.setCreateUserId((String) userInfo.get("userId"));
                fwCtiyHouseEntity.setCollecPerson((String) userInfo.get("userName"));
            }
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(cityTaskVo, fwCtiyHouseEntity);
            String delFlag="0";
            fwCtiyHouseEntity.setTaskName(taskName);
            fwCtiyHouseEntity.setTaskId(taskId);
            saveFrom(fwCtiyHouseEntity,"1");
        }
    }

    @Override
    public String findByFwId(String fwId) {
        return cityTaskRepository.findByFwId(fwId);
    }
}
